package com.wlw.eye.adapter

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Parcelable
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.wlw.eye.R
import com.wlw.eye.mvp.model.bean.VideoBean
import com.wlw.eye.ui.VideoDetailActivity
import com.wlw.eye.utils.ImageLoadUtils
import com.wlw.eye.utils.SPUtils
import com.wlw.eye.utils.showToast
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.item_download.view.*
import zlc.season.rxdownload2.RxDownload
import zlc.season.rxdownload2.entity.DownloadFlag

class DownloadAdapter(list: ArrayList<VideoBean>) : RecyclerView.Adapter<BaseHolder>() {
    var list: ArrayList<VideoBean>? = null
    lateinit var mOnLongClickListener: OnLongClickListener
    var isDownLoad = false
    var hasLoaded = false
    lateinit var disposable: Disposable

    init {
        this.list = list
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseHolder {
        return BaseHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_download, parent, false))
    }

    override fun getItemCount(): Int = list?.size ?: 0

    override fun onBindViewHolder(holder: BaseHolder, position: Int) {
        bindView(holder.itemView, list!![position], position)
    }

    private fun bindView(itemView: View, videoBean: VideoBean, position: Int) {
        videoBean.feed?.let { ImageLoadUtils.display(itemView.context, itemView.iv_photo, it) }
        itemView.tv_title.text = videoBean.title
        isDownLoad = SPUtils.getInstance(itemView.context, "download_state").getBoolea(videoBean.playUrl!!)
        getDownloadState(videoBean.playUrl!!, itemView)
        itemView.iv_downLoad_state.setImageResource(if (isDownLoad) R.mipmap.icon_download_stop else R.mipmap.icon_download_start)
        itemView.iv_downLoad_state.setOnClickListener {
            if (isDownLoad) {
                SPUtils.getInstance(itemView.context, "downLoadState").put(videoBean.playUrl!!, false)
                itemView.iv_downLoad_state.setImageResource(R.mipmap.icon_download_start)
                RxDownload.getInstance(itemView.context).pauseServiceDownload(videoBean.playUrl).subscribe()
            } else {
                SPUtils.getInstance(itemView.context, "downLoadState").put(videoBean.playUrl!!, true)
                itemView.iv_downLoad_state.setImageResource(R.mipmap.icon_download_stop)
                addMission(itemView.context, videoBean.playUrl!!, position + 1)
            }
            isDownLoad = !isDownLoad
        }
        itemView.setOnClickListener {
            val intent = Intent(itemView.context, VideoDetailActivity::class.java)
            intent.putExtra("data", videoBean as Parcelable)
            if (hasLoaded) {
                val files = RxDownload.getInstance(itemView.context).getRealFiles(videoBean.playUrl)
                val uri = Uri.fromFile(files!![position])
                intent.putExtra("localFile", uri.toString())
            }
            itemView.context.startActivity(intent)
        }
        itemView.setOnLongClickListener {
            mOnLongClickListener.onLongClick(position)
            true
        }
    }

    private fun getDownloadState(playUrl: String, itemView: View) {
        disposable = RxDownload.getInstance(itemView.context).receiveDownloadStatus(playUrl)
                .subscribe { event ->
                    if (event.flag == DownloadFlag.FAILED) {
                    }
                    val downloadStatus = event.downloadStatus
                    var percent = downloadStatus.percentNumber
                    if (percent == 100L) {
                        if (!disposable.isDisposed) {
                            disposable.dispose()
                        }
                        hasLoaded = true
                        itemView.iv_downLoad_state.visibility = View.GONE
                        itemView.tv_detail.text = "已缓存"
                        isDownLoad = false
                        SPUtils.getInstance(itemView.context, "download_state").put(playUrl, false)
                    } else {
                        if (itemView.iv_downLoad_state.visibility != View.VISIBLE)
                            itemView.iv_downLoad_state.visibility = View.VISIBLE
                        itemView.tv_detail.text = if (isDownLoad) "缓存中 / $percent%" else "已暂停 / $percent%"

                    }
                }
    }

    private fun addMission(context: Context, playUrl: String, count: Int) {
        RxDownload.getInstance(context).serviceDownload(playUrl, "download$count")
                .subscribe({
                    context.showToast("开始下载")
                }, {
                    context.showToast("添加任务失败")
                })
    }

    fun setOnLongClickListener(onLongClickListener: OnLongClickListener) {
        this.mOnLongClickListener = onLongClickListener
    }

    interface OnLongClickListener {
        fun onLongClick(position: Int)
    }
}